package com.huwaiwai.lock.semaphore;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Semaphore;

/**
 * Created by hww on 2019/1/10 3:12 PM.
 */
public class Test {

    public static void main(String [] args) throws Exception {
        test03();
    }

    private static void test01() throws InterruptedException {
        Semaphore s = new Semaphore(3);
        s.acquire(1);
        System.out.println(s.availablePermits());
        s.acquire(2);
        System.out.println(s.availablePermits());
    }

    private static void test02() {
        Runnable run = () -> {
            System.out.println(Thread.currentThread().getName() + "- start");
            DeadLoopClass d = new DeadLoopClass();
            System.out.println(Thread.currentThread().getName() + "- run over");
        };
        Thread thread1 = new Thread(run);
        Thread thread2 = new Thread(run);
        thread1.start();
        thread2.start();
    }

    private static void test03() throws Exception{
        ClassLoader classLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);

                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };
        Object obj = classLoader.loadClass("com.huwaiwai.lock.semaphore.Test").newInstance();
        System.out.println(obj.getClass());
        System.out.println(obj instanceof com.huwaiwai.lock.semaphore.Test);
    }

    static class DeadLoopClass {
        static {
            if (true) {
                System.out.println(Thread.currentThread().getName() + "init DeadLoopClass");
                while (true) {

                }
            }
        }
    }

}
